package book;

import constant.Constant;
import utils.AnalyzingBook;
import utils.ScannerSingleton;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/7/19
 * Time: 01:08
 */
public class Library {
    public Book[] books;
    public int bookCount;
    private final Scanner scanner;
    private Library() {
        loadAllBook();
        scanner = ScannerSingleton.getScanner();
    }
    private static Library library;
    public static Library getLibrary() {
        if (library == null) {
            library = new Library();
        }
        return library;
    }
    private AnalyzingBook analyzingBook = new AnalyzingBook();
    private void loadAllBook() {
        try {
            Book[] allBook = analyzingBook.loadObject(Constant.ALL_BOOK_FILE_NAME);
            books = new Book[Constant.CAPACITY];
            if (allBook == null) {
                bookCount = 0;
            }else  {
                //实际数量大
                if (allBook.length > Constant.CAPACITY) {
                    books = new Book[allBook.length];
                }
                //默认数量大于等于实际数量
                for (int i = 0; i < allBook.length; i++) {
                    books[i] = allBook[i];
                }
                //System.arraycopy(allBook, 0, books, 0, allBook.length);
                bookCount = allBook.length;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private void storeBook() {
        try {
            analyzingBook.storeObject(books,Constant.ALL_BOOK_FILE_NAME);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void addBook(Book book) {
        if (bookCount >= books.length) {
            System.out.println("书架已满,无法上架图书");
            return;
        }
        books[bookCount] = book;
        Book lastBook = books[bookCount - 1];
        book.setBookId(lastBook.getBookId() + 1);
        bookCount++;
        storeBook();
        System.out.println("图书：" + book.getTitle() + " 上架成功");
    }

    public Book searchById(int bookId){
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            if (books[i].getBookId() == bookId) {
                return books[i];
            }
        }
        System.out.println("没有找到该图书");
        return null;
    }

    private int searchByIdReturnIndex(int bookId){
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            if (books[i].getBookId() == bookId) {
                return i;
            }
        }
        return -1;
    }

    public void updateBook(Book book) {
        int index = searchByIdReturnIndex(book.getBookId());
        if (index == -1) {
            System.out.println("没有你要更新的图书：" +  book.getBookId());
            return;
        }
        books[index] = book;
        storeBook();
        System.out.println("更新成功,文件已经写入");
        System.out.println(books[index]);
    }

    public void removeBook(int bookId) {
        int index = searchByIdReturnIndex(bookId);
        if (index == -1) {
            System.out.println("没有你要删除的图书");
        }
        for (int i = index; i < bookCount - 1; i++) {
            books[i] = books[i + 1];
        }
        books[--bookCount] = null;
        storeBook();
    }

    public void borrowCount() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println(book.getTitle() + " 借阅了：" +  book.getBorrowCount() + "次");
        }
    }

    public void generateBook(int k) {
        loadAllBook();
        Book[] temp =  new Book[bookCount];
        //将books拷贝到temp
        System.arraycopy(books, 0, temp, 0, bookCount);
        Arrays.sort(temp);
        Book[] generateBooks =  new Book[k];
        //将temp拷贝到generateBooks
        System.arraycopy(temp, 0, generateBooks, 0, k);
        System.out.println("最受欢迎的前" + k + "本书如下：");
        for (int i = 0; i < k; i++) {
            System.out.println("图书Id：" + books[i].getBookId() + ",书名：" +  books[i].getTitle()
            + ",作者：" + books[i].getAuthor() + ",借阅次数：" + books[i].getBorrowCount());
        }
    }

    public void checkInventoryStatus() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            String status = "未借阅";
            if (book.isBorrow()) {
                status  = "已借阅";
            }
            System.out.println("图书：" + book.getTitle() + ",借阅状态：" + status);
        }
    }

    public void checkAndRemoveOldBooks() {
        loadAllBook();
        //获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();
        //将当前时间戳转换为LocalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        boolean flg = false;
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            //获取当前书籍的上架时间
            LocalDate specifiedDate = book.getShelfDate();
            //计算两个⽇期之间的差值(以年为单位)
            long yearsBetween = ChronoUnit.YEARS.between(specifiedDate,
                    currentDate);
            if(yearsBetween >= 1) {
                System.out.print("图书 " + book.getTitle() + " 已经上架超过⼀年,是否移除？ (y/n)：");
                scanner.nextLine();
                String response = scanner.nextLine();
                if (response.equalsIgnoreCase("y")) {
                    //确认删除调用remove⽅法进行删除
                    removeBook(book.getBookId());
                    i--; //因为后面的书已经向前移动,所以要重新检查当前索引位置
                }
                flg = true;
            }
        }
        if(!flg) {
            System.out.println("没有上架超过⼀年的图书！");
        }
    }

    public void borrowBook(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId()== bookId) {
                book.setBorrow(true);
                book.setBorrowCount(book.getBorrowCount() + 1);
            }
        }
        storeBook();
    }

    public void returnBook(int bookId) {
        loadAllBook();
        Book book = searchById(bookId);
        book.setBorrowCount(book.getBorrowCount() - 1);
        book.setBorrow(false);
        storeBook();
    }

    //公共功能
    public void searchBook() {
        scanner.nextLine();
        System.out.println("请输⼊你要查找的图书的名称：");
        String title = scanner.nextLine();
        Book book = search(title);
        if(book == null) {
            System.out.println("没有你要找的这本书,你查找的书名为："+title);
        }else {
            System.out.println("找到了你要查找的书,书的详细信息如下：");
            System.out.println(book);
        }
    }
    //根据title查找对应书籍
    private Book search(String title) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getTitle().equals(title)) {
                return book;
            }
        }
        return null;
    }
    public void displayBook() {
        loadAllBook();
        if (bookCount == 0) {
            System.out.println("书架为空");
        }
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);
        }
    }
    public void exit(){
        System.exit(0);
    }
}
